package top.smallway.lightbandassistant_app.UI.type;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class TypeUtil {
    private static final Map<Class<? extends BaseType>, Map<Integer, ? extends BaseType>> cache = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    public static <T extends Enum<T> & BaseType> T fromValue(Class<T> enumClass, int value) {
        Map<Integer, ? extends BaseType> valueMap = cache.computeIfAbsent(enumClass, cls -> {
            Map<Integer, BaseType> map = new ConcurrentHashMap<>();
            for (BaseType enumConstant : Objects.requireNonNull(cls.getEnumConstants())) {
                map.put(enumConstant.getValue(), enumConstant);
            }
            return map;
        });

        T result = (T) valueMap.get(value);
        if (result == null) {
            throw new IllegalArgumentException("Unknown value " + value + " for enum " + enumClass.getSimpleName());
        }
        return result;
    }
}
